import 'package:dio/dio.dart';
import 'package:util/result/catching.dart';
import 'package:util/result/result_extension.dart';

import '../../response/article_response.dart';
import 'home_articles_repository.dart';

class HomeArticlesRepositoryImpl implements HomeArticlesRepository {
  final Dio _dio;

  HomeArticlesRepositoryImpl({required Dio dio}) : _dio = dio;

  @override
  Future<List<ArticleResponse>> fetchHomeArticles({int page = 0}) async {
    final apiResult = await runCatchingAsync(() async {
      final url = "https://www.wanandroid.com/article/list/$page/json";
      final data = (await _dio.get(url)).data['data'];
      return (data['datas'] as List<dynamic>)
          .map((json) => ArticleResponse.fromJson(json))
          .toList();
    });
    return apiResult.getOrNull() ?? [];
  }
}
